#!/bin/bash

echo `pwd`

# 导入头文件
. ./script/ParameEngineBase.sh

#解决ArgumentError - invalid byte sequence in US-ASCII错误
#修改终端语言、地区等国际化环境变量
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
export LC_ALL=en_US.UTF-8
export PATH=$PATH:/usr/local/bin
#更换ruby环境，对应的修改有 打包机下面的  .bashrc  .zshrc .zlogin
#source $HOME/.rvm/scripts/rvm #source ~/.bashrc

MainVersion=${MainVersion}
PackageType=${PackageType}
BrachName=${BrachName}

# 切换到指定分支并拉取代码
function checkoutBranchAndPull() 
{
    git checkout ${BrachName}
    git pull
}

# 获取tag
function gitTagAutoIncrementOfGitPathAndPrefix()
{
    local tagPrefix="${1}"

    #获取版本的位数
    local pointCountStr=`echo "${tagPrefix}" |tr -cd . |wc -c | sed 's/ //g'`
    let pointCount=$((${pointCountStr}+2));

    local tagResult;
    if [[ "${pointCount}" == "4" ]]; then
        tagResult=`git tag | grep ${tagPrefix}.[0-9]* |awk -F . '{print $4}'`
    elif [[ "${pointCount}" == "5" ]]; then
        tagResult=`git tag | grep ${tagPrefix}.[0-9]* |awk -F . '{print $5}'`
    elif [[ "${pointCount}" == "6" ]]; then
        tagResult=`git tag | grep ${tagPrefix}.[0-9]* |awk -F . '{print $6}'`
    fi
    # 判断执行结果
    # resultVerifySuccess_result_errorInfo "$?" ${FUNCNAME} "git tag获取失败...."

    local tagList=($tagResult)
	local biggestTagNum=0
	for oneTagNum in ${tagList[@]}
	do
		#是否是数字判断
		if [[ "${oneTagNum}" != *[!0-9]* ]]; then
			if [ $biggestTagNum -lt $oneTagNum ]
			then
				biggestTagNum=$oneTagNum
			fi
		else
			echo "${oneTagNum} has a non-digit somewhere in it"
			echo "存在末尾不是数字的Tag，请检查....error...."
			exit 1
		fi
	done

	let "buildVersion = $biggestTagNum + 1"
	echo "${buildVersion}"
}

function addGitTag()
{
    local tagShowStr="${1}"

    echo $tagShowStr
    git tag $tagShowStr
    resultVerifySuccess_result_errorInfo "$?" "${FUNCNAME}" "添加tag失败！..."

    # git push origin $tagShowStr
    # resultVerifySuccess_result_errorInfo "$?" "${FUNCNAME}" "推送tag到远程失败！..."
}

checkoutBranchAndPull
buildVersion=`gitTagAutoIncrementOfGitPathAndPrefix "${MainVersion}"`
version="${MainVersion}.${buildVersion}"
echo "当前tag:${version}"
addGitTag "${version}"

#解锁keychain，是其它工具可以访问证书，解锁后设置keychain关闭时间为1小时, xxx为用户名
#security -v unlock-keychain -p "sun" "/Users/sun/Library/Keychains/login.keychain"
#security set-keychain-settings -t 3600 -l "/Users/sun/Library/Keychains/login.keychain"
#/usr/local/bin/pod update --verbose --no-repo-update
#
# fastlane profile
if [[ ${PackageType} == "Debug" ]]; then
    bundle exec fastlane iosDevelopment buildVersion:"${version}"
elif [[ ${PackageType} == "AdHoc" ]]; then
    bundle exec fastlane iosAdHoc buildVersion:"${version}"
elif [[ ${PackageType} == "AppStore" ]]; then
    bundle exec fastlane iosAppStore buildVersion:"${version}"
fi
